import {
  getLabelList,
  removeLabel
} from "../../apis/label";
import {
  globalData
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    labelList: [],
    pageNum: 1,
    isHaveMore: true,
    isRequest: false
  },

  onLoad() {
    this.setData({
      showGroupBtn: globalData.checkIn
    });
  },

  onShow() {
    this.setData({
      pageNum: 1,
      isHaveMore: true
    });
    this.getLabel(1, 10, 'refresh');
  },

  onReachBottom() {
    if (this.data.isHaveMore) {
      this.setData({
        pageNum: this.data.pageNum + 1
      });
    };
    this.getLabel(1, 10);
  },

  getLabel(pageNum, pageSize, type) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    getLabelList(pageNum, pageSize).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        if (type === 'refresh') {
          this.setData({
            labelList: rows
          });
        } else {
          rows.forEach(v => {
            this.data.labelList.push(v);
          });
          this.setData({
            labelList: this.data.labelList
          });
        };

        if (this.data.labelList.length === total) {
          this.setData({
            isHaveMore: false
          });
        };
      };
    });
  },

  deleteLabel(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.showModal({
      title: '删除标签',
      content: '确定删除标签吗',
      success: res => {
        if (res.confirm) {
          removeLabel(id).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                success: () => {
                  this.getLabel(this.data.labelList.length + 1, 1, 'refresh');
                }
              });
            };
          });
        };
      }
    });
  },

  addTag() {
    wx.showActionSheet({
      itemList: ['家人', '同事', '同学', '同乡'],
      success: res => {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: '/pages/groupEdit/index?from=label&type=create&label=家人',
          });
        } else if (res.tapIndex === 1) {
          wx.navigateTo({
            url: '/pages/groupEdit/index?from=label&type=create&label=同事',
          });
        } else if (res.tapIndex === 2) {
          wx.navigateTo({
            url: '/pages/groupEdit/index?from=label&type=create&label=同学',
          });
        } else if (res.tapIndex === 3) {
          wx.navigateTo({
            url: '/pages/groupEdit/index?from=label&type=create&label=同乡',
          });
        };
      }
    });
  }
})